#include "AtomFeed.h"

#include <libxml++/libxml++.h>
#include <glibmm/unicode.h>

#include <vector>

using namespace xmlpp;
using namespace Glib;


AtomFeed::AtomFeed()
{
}

AtomFeed::~AtomFeed()
{
}

static string getTextAtPath(Element * el, string xpath)
{
    map < ustring, ustring > ns;
    ns["atom"] = "http://www.w3.org/2005/Atom";

    NodeSet nodes = el->find(xpath, ns);

    if (nodes.size() > 0) {
	Node *node = (Node *) (nodes[0]);
	Attribute *attribute = dynamic_cast < Attribute * >(node);
	if (attribute)
	    return attribute->get_value();

	Element *element = dynamic_cast < Element * >(node);
	if (element) {
	    TextNode *text = element->get_child_text();
	    if (text)
		return text->get_content();
	}
    }

    return "";
}

static Post readPost(Element * el)
{
    Post p;
    p.title = getTextAtPath(el, "atom:title");
    p.link = getTextAtPath(el, "atom:link/@href");
    p.content = getTextAtPath(el, "atom:content");
    p.description = getTextAtPath(el, "atom:description");
    p.author = getTextAtPath(el, "atom:author/atom:name");
    return p;
}

AtomFeed AtomFeed::FromXml(string xml)
{
    AtomFeed feed;
    DomParser parser;

    parser.parse_memory(xml.data());

    Element *root = parser.get_document()->get_root_node();

    vector < Post > posts;

    feed.title = getTextAtPath(root, "atom:title");
    feed.description = getTextAtPath(root, "atom:subtitle");
    feed.author = getTextAtPath(root, "atom:author/atom:name");
    feed.pageUrl =
	getTextAtPath(root, "atom:link[@type='text/html']/@href");

    map < ustring, ustring > ns;
    ns["atom"] = "http://www.w3.org/2005/Atom";
    vector < Node * >children = root->find("atom:entry", ns);
    for (vector < Node * >::iterator i = children.begin();
	 i != children.end(); i++) {
	Node *node = *i;
	if (dynamic_cast < Element * >(node)) {
	    Element *el = dynamic_cast < Element * >(node);
	    Post post = readPost(el);
	    posts.push_back(post);
	}
    }
    feed.setPosts(posts);

    return feed;
}
